package com.wholesale;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils.TruncateAt;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.paypal.android.MEP.CheckoutButton;
import com.paypal.android.MEP.PayPal;
import com.paypal.android.MEP.PayPalPayment;
import com.wholesale.beans.Country;
import com.wholesale.beans.Order;
import com.wholesale.beans.OrderDetail;
import com.wholesale.datas.ResultDelegate;
import com.wholesale.datas.WebServiceClient;
import com.wholesale.utils.Constants;
import com.wholesale.utils.Maths;
import com.wholesale.utils.MyOrderListAdapter;

public class MyOrdersDetailLayout extends LinearLayout implements
		OnClickListener, Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6265414483804827386L;
	// The PayPal server to be used - can also be ENV_NONE and ENV_LIVE
	public static final int server = PayPal.ENV_LIVE;
	// This is passed in for the startActivityForResult() android function, the
	// value used is up to you
	public static final int request = 1;

	private static MyOrdersDetailLayout currentInstance;
	private static ViewFlipper viewFlipper;
	private static Context context;
	private View baseView;
	private Button leftButton;
	private Button rightButton;
	private TextView headView;
	private MyOrderListAdapter listAdapter;
	private TextView goodsSn, consignee, phone, address, zipcode, orderstatus,
			shippingmethod, paymethod, generation, delivery, goodsid,
			goodsName, number, price, goodprice, shippingfee, totalprice,
			country, province, city, payTime, useBalance;
	private int orderid;
	private static Order order;
	private MyOrdersDetailAsync detailAsy;
	private RelativeLayout loadingLayout;
	private ScrollView scrollView;
	private LinearLayout goodsLayout;
	private LinearLayout paypalLayout;
	private LinearLayout loadingPaypalLayout;
	private boolean isPaypal = false;

	public static Handler paypalHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 接收来自paypal的消息
			if (msg.what == 2000) {
				// 0-success 1-failed 2-cancle
				int a = 0;
				a = 2;
				switch (msg.arg1) {
				case 0:
					// success
					boolean result = WebServiceClient.setPaypalId(
							order.getOrderSn(), (String) msg.obj,
							order.getUserId(),
							Constants.loginResponse.getUserToken());
					if (result) {
						Toast.makeText(context, "payment success.", 3000)
								.show();
					} else {
						Toast.makeText(context,
								"error,but payment success. Pls Contact Us!",
								9000).show();
					}
					viewFlipper.showPrevious();
					try {
						MyOrdersLayout myOrderView = (MyOrdersLayout) viewFlipper
								.getCurrentView();
						myOrderView.refreshMyOrders();
					} catch (Exception e) {
						e.printStackTrace();
					}
					viewFlipper.removeView(currentInstance);

					break;
				case 1:
					// failed
					Toast.makeText(context, "payment failed. please retry it.",
							8000).show();
					viewFlipper.showPrevious();
					viewFlipper.removeView(currentInstance);
					break;
				case 2:
					// cancle
					Toast.makeText(context, "payment canceled.", 6000).show();
					viewFlipper.showPrevious();
					viewFlipper.removeView(currentInstance);
					break;
				}
			}
		}
	};

	public Handler initHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 2001) {
				// 生成按钮
				initPaypalButton();
			}
		};
	};

	// 构造函数
	public MyOrdersDetailLayout(Context context, final ViewFlipper viewFlipper,
			int orderid, Order order) {
		super(context);
		currentInstance = this;
		MyOrdersDetailLayout.viewFlipper = viewFlipper;
		MyOrdersDetailLayout.context = context;
		this.orderid = orderid;
		MyOrdersDetailLayout.order = order;
		// 加载需要的属性，加载方法一的子Layout
		baseView = ((Activity) getContext()).getLayoutInflater().inflate(
				R.layout.myorderdetail, this);
		leftButton = (Button) baseView.findViewById(R.id.leftBtn);
		leftButton.setText("My orders");
		leftButton.setOnClickListener(this);
		rightButton = (Button) baseView.findViewById(R.id.rightBtn);
		rightButton.setVisibility(View.INVISIBLE);
		headView = (TextView) baseView.findViewById(R.id.title);
		headView.setText("Order detail");
		scrollView = (ScrollView) baseView.findViewById(R.id.scrollView1);
		scrollView.setVisibility(View.GONE);
		loadingLayout = (RelativeLayout) baseView
				.findViewById(R.id.loadingLayout);
		goodsSn = (TextView) findViewById(R.id.goodssn_text);
		consignee = (TextView) findViewById(R.id.consignee_text);
		phone = (TextView) findViewById(R.id.phone_text);
		address = (TextView) findViewById(R.id.address_text);
		zipcode = (TextView) findViewById(R.id.zipcode_text);
		orderstatus = (TextView) findViewById(R.id.goodstatus_text);
		shippingmethod = (TextView) findViewById(R.id.shipping_text);
		paymethod = (TextView) findViewById(R.id.pay_text);
		generation = (TextView) findViewById(R.id.generation_text);
		delivery = (TextView) findViewById(R.id.delivery_text);
		paypalLayout = (LinearLayout) baseView.findViewById(R.id.layout_paypal);
		goodsLayout = (LinearLayout) baseView.findViewById(R.id.goodsLayout);
		loadingPaypalLayout = (LinearLayout) baseView
				.findViewById(R.id.linearLayoutLoadingPaypal);
		useBalance = (TextView) baseView
				.findViewById(R.id.usebalanceOrderDetail_text);

		goodprice = (TextView) findViewById(R.id.goodprice_text);
		shippingfee = (TextView) findViewById(R.id.shippingfee_text);
		totalprice = (TextView) findViewById(R.id.total_text);
		country = (TextView) findViewById(R.id.country_text);
		province = (TextView) findViewById(R.id.province_text);
		city = (TextView) findViewById(R.id.city_text);

		// add by dave
		payTime = (TextView) baseView.findViewById(R.id.paytime2_text);

		detailAsy = new MyOrdersDetailAsync(context);
		detailAsy.execute(false);
		initPaypal(order);
	}

	private void initPaypal(Order order) {
		if (order.getPayStatus() == 0
				&& order.getPayName().equalsIgnoreCase(
						"Paypal (Credit Card / Debit Card)")) {
			isPaypal = true;
			Thread t = new Thread() {
				@Override
				public void run() {
					initLibrary();
					initHandler.sendEmptyMessage(2001);
				}
			};
			t.start();
			loadingPaypalLayout.setVisibility(View.VISIBLE);
		}
	}

	CheckoutButton paymentBtn;

	private void initPaypalButton() {
		if (isPaypal) {
			// 生成按钮
			try {
				paypalLayout.removeView(paymentBtn);
			} catch (Exception e) {
			}
			loadingPaypalLayout.setVisibility(View.GONE);
			PayPal pp = PayPal.getInstance();
			paymentBtn = pp.getCheckoutButton(context, PayPal.BUTTON_194x37,
					CheckoutButton.TEXT_PAY);
			paymentBtn.setOnClickListener(this);
			paymentBtn.setGravity(Gravity.CENTER_HORIZONTAL);
			paypalLayout.addView(paymentBtn);
		}
	}

	private void doPalpayPay() {
		double payAmount = Maths.sub(
				Maths.add(order.getGoodsAmount(),
						Constants.getTwoDecimalFloor(order.getShippingFee())),
				order.getSurplus());
		PayPalPayment payment = new PayPalPayment();
		payment.setCurrencyType("USD");
		payment.setRecipient(Constants.paypalReceiver);
		payment.setSubtotal(new BigDecimal(payAmount));
		payment.setPaymentType(PayPal.PAYMENT_TYPE_GOODS);
		payment.setMerchantName("Wholesale dress");
		payment.setDescription("WholeSale Payment");
		payment.setCustomID("8873482296");
		payment.setIpnUrl("http://www.exampleapp.com/ipn");
		Intent checkoutIntent = PayPal.getInstance().checkout(payment, context,
				new ResultDelegate());
		((Activity) context).startActivityForResult(checkoutIntent, request);
	}

	private void initLibrary() {
		PayPal pp = PayPal.getInstance();
		if (pp == null) {
			pp = PayPal.initWithAppID(context, Constants.paypalAppId, server);
			pp.setLanguage("en_US");
			pp.setFeesPayer(PayPal.FEEPAYER_EACHRECEIVER);
			pp.setShippingEnabled(false);
			pp.setDynamicAmountCalculationEnabled(false);
		}
	}

	// ListView 点击事件
	OnItemClickListener moreClieckListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			OrderDetailLayout orderDetailLayout = new OrderDetailLayout(
					context, viewFlipper, 0);
			viewFlipper.addView(orderDetailLayout);
			viewFlipper.showNext();
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.leftBtn:
			viewFlipper.showPrevious();
			viewFlipper.removeView(this);
			break;
		default:
			break;
		}
		if (v instanceof CheckoutButton) {
			doPalpayPay();
		}

	}

	class GoodsOnClick implements View.OnClickListener {
		private int goodsId;

		public GoodsOnClick(int goodsId) {
			this.goodsId = goodsId;
		}

		@Override
		public void onClick(View v) {
			GoodsDetailLayout goodsDetailLayout = new GoodsDetailLayout(
					context, viewFlipper, "Order detail", goodsId);
			viewFlipper.addView(goodsDetailLayout);
			viewFlipper.showNext();
		}

	}

	class MyOrdersDetailAsync extends
			AsyncTask<Boolean, Integer, ArrayList<OrderDetail>> {
		ProgressDialog pdialog;
		String countryName = "";
		String provinceName = "";
		String cityName = "";

		public MyOrdersDetailAsync(Context context) {

		}

		@Override
		protected void onPreExecute() {
			loadingLayout.setVisibility(View.VISIBLE);
		}

		@Override
		protected ArrayList<OrderDetail> doInBackground(Boolean... params) {
			int size = 0;
			List<Country> countryList;
			if (order.getCountry() != 0) {
				countryList = WebServiceClient.getCountries();
				size = countryList.size();
				for (int i = 0; i < size; i++) {
					if (countryList.get(i).getRegionId() == order.getCountry()) {
						countryName = countryList.get(i).getRegionName();
						break;
					}
				}
			}
			if (order.getProvince() != 0) {
				countryList = WebServiceClient.getRegionByParentParentId(
						order.getCountry(), 1);
				size = countryList.size();
				for (int i = 0; i < size; i++) {
					if (countryList.get(i).getRegionId() == order.getProvince()) {
						provinceName = countryList.get(i).getRegionName();
						break;
					}
				}
			}
			if (order.getCity() != 0) {
				countryList = WebServiceClient.getRegionByParentParentId(
						order.getProvince(), 2);
				size = countryList.size();
				for (int i = 0; i < size; i++) {
					if (countryList.get(i).getRegionId() == order.getCity()) {
						cityName = countryList.get(i).getRegionName();
						break;
					}
				}
			}
			return WebServiceClient.getOrderDetail(orderid,
					Constants.loginResponse.getUserId(),
					Constants.loginResponse.getUserToken());
		}

		@Override
		protected void onPostExecute(ArrayList<OrderDetail> result) {
			int size = result.size();
			OrderDetail orderDetail;
			TableRow.LayoutParams rowLayout = new TableRow.LayoutParams(
					TableRow.LayoutParams.WRAP_CONTENT,
					TableRow.LayoutParams.WRAP_CONTENT);
			rowLayout.bottomMargin = 10;
			rowLayout.topMargin = 10;
			DisplayMetrics dm = new DisplayMetrics();
			((Activity) getContext()).getWindowManager().getDefaultDisplay()
					.getMetrics(dm);
			// rowLayout.setMargins(0, 20, 0, 20);
			for (int i = 0; i < size; i++) {
				orderDetail = result.get(i);
				if (i == 0) {
					goodsSn.setText(orderDetail.getGoodsSn());
				}
				TableLayout tableLayout = new TableLayout(context);
				int textWidth = (int) (dm.widthPixels * 0.65);
				// 添加goodsId
				TableRow idRow = new TableRow(context);
				TextView goodsIdLable = new TextView(context);
				goodsIdLable.setText("GoodsSn:");
				goodsIdLable.setTextColor(Color.BLACK);
				idRow.addView(goodsIdLable);
				TextView goodsIdText = new TextView(context);
				goodsIdText.setText(orderDetail.getGoodsSn());
				goodsIdText.setTextColor(Color.BLACK);
				idRow.addView(goodsIdText);
				tableLayout.addView(idRow, rowLayout);
				// 添加goodsName
				TableRow nameRow = new TableRow(context);
				TextView goodsNameLable = new TextView(context);
				// goodsNameLable.setWidth(115);
				goodsNameLable.setText("Name:");
				goodsNameLable.setTextColor(Color.BLACK);
				nameRow.addView(goodsNameLable);
				TextView goodsNameText = new TextView(context);
				goodsNameText.setWidth(textWidth);
				goodsNameText.setSingleLine(false);
				goodsNameText.setEllipsize(TruncateAt.END);
				goodsNameText.setText(orderDetail.getGoodsName());
				goodsNameText.setTextColor(Color.BLACK);
				nameRow.addView(goodsNameText);
				tableLayout.addView(nameRow, rowLayout);
				String goodsAttr = orderDetail.getGoodsAttr();

				// 添加goods 属性
				if (goodsAttr != null && !goodsAttr.equals("")) {
					goodsAttr = goodsAttr.replaceAll(",", "\n");
					goodsAttr = goodsAttr.replaceAll(";", "\n");
					TableRow attrRow = new TableRow(context);
					TextView attrLable = new TextView(context);
					attrLable.setText("Attribute:");
					attrLable.setTextColor(Color.BLACK);
					attrRow.addView(attrLable);
					TextView attrText = new TextView(context);
					attrText.setWidth(textWidth);
					attrText.setSingleLine(false);
					// attrText.setEllipsize(TruncateAt.MARQUEE);
					attrText.setText(goodsAttr);
					attrText.setTextColor(Color.BLACK);
					attrRow.addView(attrText);
					tableLayout.addView(attrRow, rowLayout);

					// comment by dave

					// String[] strs = goodsAttr.split("\n");
					// String value;
					// for (int n = 0; n < strs.length; n++) {
					// value = strs[n];
					// String name = value.split(":")[0].trim();
					// TableRow attrRow = new TableRow(context);
					// TextView attrLable = new TextView(context);
					// attrLable.setText(name + ":");
					// attrLable.setTextColor(Color.BLACK);
					// attrRow.addView(attrLable);
					// TextView attrText = new TextView(context);
					// name = value.split(":")[1].trim();
					// if (customSize > 0 && customSize < 5) {
					// name = name + " cm";
					// }
					// attrText.setText(name);
					// attrText.setTextColor(Color.BLACK);
					// attrRow.addView(attrText);
					// tableLayout.addView(attrRow, rowLayout);
					// if (customSize == 0) {
					// if (name.equalsIgnoreCase("custom size")) {
					// customSize = customSize + 1;
					// }
					// }
					// }
				}
				// countRow
				TableRow countRow = new TableRow(context);
				TextView numberLable = new TextView(context);
				String html = "Quantity:  <font color=#ff0000>"
						+ orderDetail.getGoodsNumber() + " </font>";
				numberLable.setText(Html.fromHtml(html));
				numberLable.setTextColor(Color.BLACK);
				countRow.addView(numberLable);
				TextView totalText = new TextView(context);
				html = "Subtotal:  <font color=#ff0000>"
						+ "US$ "
						+ Maths.mul(orderDetail.getGoodsNumber(),
								orderDetail.getGoodsPrice()) + " </font>";
				totalText.setText(Html.fromHtml(html));
				totalText.setTextColor(Color.BLACK);
				countRow.addView(totalText);
				tableLayout.addView(countRow, rowLayout);
				tableLayout.setOnClickListener(new GoodsOnClick(orderDetail
						.getGoodsId()));
				goodsLayout.addView(tableLayout);
				ImageView imageView = new ImageView(context);
				imageView.setBackgroundResource(R.drawable.middle_line);
				imageView.setLayoutParams(new LinearLayout.LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT,
						1.0f));
				imageView.layout(-10, 10, -10, 10);
				goodsLayout.addView(imageView);
			}
			if (order.getConsignee() != null) {
				consignee.setText(order.getConsignee());
			}
			if (order.getMobile() != null) {
				phone.setText(order.getMobile());
			}
			if (order.getAddress() != null) {
				address.setText(order.getAddress());
			}
			if (order.getZipcode() != null) {
				zipcode.setText(order.getZipcode());
			}
			if (order.getOrderStatusName() != null) {
				orderstatus.setText(order.getOrderStatusName());
			}
			if (order.getShippingName() != null) {
				shippingmethod.setText(order.getShippingName());
			}
			if (order.getPayName() != null) {
				paymethod.setText(order.getPayName());
			}
			if (order.getAddTime() != null) {
				generation.setText(order.getAddTime());
			}
			if (order.getPayTime() != null && !order.getPayTime().equals("")) {
				payTime.setText(order.getPayTime());
			}
			if (order.getShippingTime() != null) {
				delivery.setText(order.getShippingTime());
			}
			goodprice.setText("US$ " + order.getGoodsAmount());
			shippingfee.setText("US$ "
					+ Constants.getTwoDecimalFloor(order.getShippingFee()));
			totalprice.setText("US$ "
					+ Maths.add(order.getGoodsAmount(), +Constants
							.getTwoDecimalFloor(order.getShippingFee())));
			useBalance.setText("US$ " + order.getSurplus());
			country.setText(countryName);
			province.setText(provinceName);
			city.setText(cityName);

			// 设置shouldpay
			if (order.getPayStatus() == 0) {
				((TextView) baseView.findViewById(R.id.detailShouldpay_text))
						.setText("US$ " + order.getOrderAmount());
			} else {
				baseView.findViewById(R.id.tableRowMyOrderDetailShouldPay)
						.setVisibility(View.GONE);
			}

			scrollView.setVisibility(View.VISIBLE);
			loadingLayout.setVisibility(View.GONE);
			if (isPaypal) {
				paypalLayout.setVisibility(View.VISIBLE);
			}
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}
	}

}
